<template>
  <el-dialog
    title="提示"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="clickCancel"
    top="5vh"
    width="800px">
    <h3 slot="title">进账明细</h3>
    <el-row style="margin-bottom: 12px">
      <el-col :span="8" :offset="8" style="display: flex;justify-content: center">
        <el-button @click="clickCancel" plain>取 消</el-button>
        <el-button type="primary" @click="saveTableData">确 认</el-button>
      </el-col>
      <el-col :span="8" style="display: flex;justify-content: flex-end">
        <el-button icon="el-icon-plus" type="primary" @click="addTableCol">新增</el-button>
      </el-col>
    </el-row>
      <el-table
        ref="incomeDetailTableRefs"
        :data="tableData"
        :header-cell-style="{background:'#F5F7FA'}"
        style="width: 100%;margin-bottom: 30px"
        v-loading="dataListLoading"
        :summary-method="getSummaries"
        sum-text="总计"
        show-summary
        border>
        <el-table-column
          prop="typeId"
          label="类型"
          align="center"
        width="100">
          <template slot-scope="scope">
            <el-select v-model="scope.row.typeId" >
              <el-option v-for="item in typeOptions"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">

              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="科目/说明"
          align="center">
           <template slot-scope="scope">
             <el-input  v-if="scope.row.typeId !== 1" v-model="scope.row.explain"></el-input>
             <el-select v-else v-model="scope.row.projectId" placeholder="请选择科目" filterable>
               <el-option v-for="item in projectOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">

               </el-option>
             </el-select>
           </template>
        </el-table-column>

        <el-table-column
          prop=""
          label="单价(元)"
          align="center"
        width="120">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.perPrice" :min="0" type="number"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="数量"
          align="center"
          width="100">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.num" :min="0" :step="1" type="number" ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="小计(元)"
          align="center"
          width="120"
        show-overflow-tooltip>
          <template slot-scope="scope" >
            {{scope.row.perPrice * scope.row.num}}
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="税点(元)"
          align="center"
        width="100">
          <template slot-scope="scope">
            <el-input placehodlder="请输入税点" v-model.number="scope.row.tax" :min="0" type="number"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="操作"
          align="center"
        width="60">
          <template slot-scope="scope">
            <el-button type="text" style="color: #E96E6E" @click="clearCol(scope)">清空</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="detail">
        <h4>明细 <span>进款总额：{{getIncome()}}</span></h4>
        <p>{{getIncomeText()}}</p>
        <p>{{getAttachText()}}</p>
        <p>{{getRefundText()}}</p>
      </div>
  </el-dialog>
</template>

<script>
import {getDictList} from '../../../../api/customer/commom'
// import {cloneDeep} from 'lodash/cloneDeep'
const cloneDeep = require('lodash/cloneDeep')
export default {
  name: 'IncomeDetail',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  created () {
    this.getProjectsOptionsReq()
  },
  data () {
    return {
      dataListLoading: false,
      initTableData: [{
        typeId: 1,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 1,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 1,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 2,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 2,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 2,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 3,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 3,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 3,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }],
      oldTableData: [{
        typeId: 1,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 1,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 1,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 2,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 2,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 2,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 3,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 3,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 3,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }],
      visible: this.dialogVisible,
      detailText: {
        income: '',
        attach: '',
        refund: ''
      },
      newColItem: {
        typeId: 1,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      },
      typeOptions: [{
        id: 1,
        name: '进款'
      }, {
        id: 2,
        name: '挂靠'
      }, {
        id: 3,
        name: '退款'
      }],
      projectOptions: [],
      // 1-进款 2-退款 3-挂靠
      tableData: [{
        typeId: 1,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 1,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 1,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 2,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 2,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 2,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 3,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 3,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }, {
        typeId: 3,
        projectId: '',
        perPrice: '',
        explain: '',
        num: 1,
        tax: 0
      }]
    }
  },
  methods: {
    initData () {
      this.tableData = cloneDeep(this.initTableData)
    },
    hideDialog () {
      this.visible = false
      this.$emit('dialogVisibleChange', false)
    },
    getProjectsOptionsReq () {
      let dataForm = {'dictCode': 'customerCooperationsubjectId'}
      getDictList(dataForm, ({data}) => { this.projectOptions = data })
    },
    // 返回tableData
    saveTableData () {
      let textList = []
      let incomeDetailData = {}
      textList[0] = {typeName: '进款', content: this.getIncomeText()}
      textList[1] = {typeName: '挂靠', content: this.getAttachText()}
      textList[2] = {typeName: '退款', content: this.getRefundText()}
      incomeDetailData['textList'] = textList
      incomeDetailData['tableData'] = this.tableData.filter((item) => {
        if (item.perPrice !== '' && item.num !== '' && item.tax !== '') {
          return item
        }
      })
      // suntotal 为小计总和
      incomeDetailData['subtotal'] = this.getSubtotal
      // sum 为小计与税点的和
      incomeDetailData['sum'] = this.getIncome()
      // console.log('incomeDetailData', incomeDetailData)
      this.$emit('getIncomeDetailData', incomeDetailData)
      // this.oldTableData = this.tableData.map(item => this.getNewObj(item))
      this.oldTableData = cloneDeep(this.tableData)
      this.hideDialog()
    },
    // 传入模板返回不同引用的对象
    getNewColItem (newCol) {
      let col = {}
      if (newCol) {
        Object.keys(newCol).forEach((key) => {
          col[key] = newCol[key]
        })
        return col
      } else {
        return {}
      }
    },
    // 合计行计算函数
    getSummaries (param) {
      // console.log('param', param)
      const {columns} = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        if (column.label === '小计(元)') {
          sums[index] = this.getSubtotal
        } else if (column.label === '税点(元)') {
          sums[index] = this.getTax
        }
      })
      return sums
    },
    clickCancel () {
      this.$confirm('您是否要取消此次编辑？', '提示', {
        confirmButtonText: '确认保存',
        cancelButtonText: '取消保存',
        type: 'warning',
        closeOnClickModal: false,
        showClose: false
      }).then(() => {
        this.saveTableData()
        this.hideDialog()
      }).catch(() => {
        // this.tableData = this.oldTableData.map(item => this.getNewObj(item))
        this.tableData = cloneDeep(this.oldTableData)
        this.hideDialog()
      })
    },
    getNewObj (obj = {}) {
      return JSON.parse(JSON.stringify(obj))
    },
    addTableCol () {
      const newCol = this.getNewColItem(this.newColItem)
      this.tableData.push(newCol)
    },
    clearCol (scope) {
      this.$confirm('您是否要清空此行数据？', '提示', {
        cancelButtonText: '取 消',
        confirmButtonText: '确 认',
        type: 'warning'
      }).then(() => {
        // console.log('rows', scope.row)
        let colIndex = scope.$index
        let colItem = this.getNewColItem(this.newColItem)
        colItem['typeId'] = scope.row.typeId
        // console.log('colItem', colItem)
        this.$set(
          this.tableData,
          colIndex,
          colItem
        )
      })

/*      let colIndex = row.$index
      this.$set(
        this.tableData,
        colIndex,
        this.newColItem
      ) */
    },
    // 获取进款，挂靠，退款文本
    getIncomeText () {
      let incomesText = ''
      const incomes = this.tableData.filter((item) => item.typeId === 1)
      incomes.forEach((item) => {
        if (item.perPrice !== '' && item.num !== '' && item.tax !== '') {
          let option = this.projectOptions.filter(option => option.id === item.projectId)[0]
          incomesText += `${option.name}${item.num}人，小计${item.perPrice * item.num}，税点${item.tax}; `
        }
      })
      if (incomesText) {
        incomesText = '进款：' + incomesText
      }
      return incomesText
    },
    getAttachText () {
      let incomesText = ''
      const incomes = this.tableData.filter((item) => item.typeId === 2)
      incomes.forEach((item) => {
        if (item.perPrice !== '' && item.num !== '' && item.tax !== '') {
          incomesText += `${item.explain}，${item.num}人，小计${item.perPrice * item.num}，税点${item.tax}; `
        }
      })
      if (incomesText) {
        incomesText = '挂靠：' + incomesText
      }
      return incomesText
    },
    getRefundText () {
      let incomesText = ''
      const incomes = this.tableData.filter((item) => item.typeId === 3)
      incomes.forEach((item) => {
        if (item.perPrice !== '' && item.num !== '' && item.tax !== '') {
          incomesText += `${item.explain}，${item.num}人，小计${item.perPrice * item.num}，税点${item.tax}; `
        }
      })
      if (incomesText) {
        incomesText = '退款：' + incomesText
      }
      return incomesText
    },
    // 计算进款总额
    getIncome () {
      return this.getSubtotal + this.getTax
    }
  },
  computed: {
    // 计算小计
    getSubtotal () {
      if (this.tableData) {
        const values = this.tableData.map((item) => {
          if (item.typeId === 3) {
            return 0 - item.perPrice * item.num
          } else {
            return item.perPrice * item.num
          }
        })
        return values.reduce((acc, cur) => {
          return acc + cur
        }, 0)
      } else {
        return ''
      }
    },
    // 计算税点
    getTax () {
      if (this.tableData) {
        const values = this.tableData.map((item) => {
          if (item.tax) {
            if (item.typeId === 3) {
              return 0 - item.tax
            }
            return Number(item.tax)
          } else { return 0 }
        })
        return values.reduce((acc, cur) => {
          return acc + cur
        }, 0)
      } else {
        return ''
      }
    }

  },
  watch: {
    dialogVisible (val) {
      this.visible = val
      // this.tableData = this.oldTableData
    },
    data: {
      handler: function (val, oldVal) {
        const {row} = val
        // console.log('data', val)
        // console.log('row', row)
        // console.log('index', index)
        if (row.incomeDetailList) {
          this.tableData = row.incomeDetailList.map((item) => {
            let colItem = {}
            colItem['num'] = item.amount
            colItem['projectId'] = item.subjectId
            colItem['explain'] = item.explain
            colItem['tax'] = item.tax
            colItem['typeId'] = item.typeId
            colItem['perPrice'] = item.unitPrice
            return colItem
          })
        } else {
          this.tableData = cloneDeep(this.initTableData)
        }
      },
      deep: true
    }

  }
}
</script>

<style lang="less" scoped>
.btn-group{
  display: flex;
}
.detail{
  margin-left: 100px;
  margin-right: 150px;
  h4{
    margin-bottom: 5px;
  }
  p{
    margin-bottom: 3px;
    word-break:normal;
    text-indent: -3em;
    margin-left: 3em;
  }
}
</style>
